jQuery 是個好東西,對學習來說是這樣。前面的 JS 原生 API,通常都很長 document....之類的,jQuery 大大的節省了很多空間,並且閱讀 jQuery的 source code,是一個很好的認識 JS 的範本。
這邊順便記錄一些 Ajax 相關的紀錄
Key Word: Using jQuery Core, Ajax, Plugins
$
vs $()
$(document).ready()
: 網頁 執行完 DOM 部分,才會執行 Javascript 的部分$(window).on ("onload", function (){})
: 網頁執行完所有的事情 (image 或 iframes,不只是 DOM) 才會開始執行$( "form :checked" );
// Not work
var response;
$.get( "foo.php", function( r ) {
response = r;
});
console.log( response ); // undefined
// Need to pass a callback function
$.get( "foo.php", function( response ) {
console.log( response ); // server response
});
$.ajax()
: 建立 Ajax requests<body>
<div>
<span onclick="getData();">第一次</span>
<span>跟其他網頁要資料</span>
</div>
<hr/>
<div id="content"></div>
<script type="text/javascript">
var req = new XMLHttpRequest();
req.open("get", "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.places%20where%20text%3D%22san%20francisco%2C%20ca%22&format=json&diagnostics=true&callback=");
req.onload = function() {
//連線完成
var content = document.getElementById("content");
content.innerHTML = this.responseText;
}
req.send();
</script>
</body>
/^\d*$/
? MDN Regex 正規表達式
$.fn.greenify = function() {
this.css( "color", "green" );
};
$( "a" ).greenify(); // Makes all the links green.
//Chaining
$.fn.greenify = function() {
this.css( "color", "green" );
return this;
}
$( "a" ).greenify().addClass( "greenified" );
$
Alias and Adding Scope: 避免小工具的衝突設計
(function ( $ ) {
var shade = "#556b2f";
$.fn.greenify = function() {
this.css( "color", shade );
return this;
};
}( jQuery ));
$.fn
//簡化前
(function( $ ) {
$.fn.openPopup = function() {
// Open popup code.
};
$.fn.closePopup = function() {
// Close popup code.
};
}( jQuery ));
//簡化後
(function( $ ) {
$.fn.popup = function( action ) {
if ( action === "open") {
// Open popup code.
}
if ( action === "close" ) {
// Close popup code.
}
};
}( jQuery ));
each()
方法:如果想對個別元素使用 plugin,可以用 each()
$.fn.myNewPlugin = function() {
return this.each(function() {
// Do something to each element here.
});
};
(function ( $ ) {
$.fn.greenify = function( options ) {
// This is the easiest way to have default options.
var settings = $.extend({
// These are the defaults.
color: "#556b2f",
backgroundColor: "white"
}, options );
// Greenify the collection based on the settings variable.
return this.css({
color: settings.color,
backgroundColor: settings.backgroundColor
});
};
}( jQuery ));
//使用
$( "div" ).greenify({
color: "orange"
});